package cn.tedu.ivos.geofence.service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.geofence.mapper.GeofenceMapper;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceParam;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceQuery;
import cn.tedu.ivos.geofence.pojo.entity.Geofence;
import cn.tedu.ivos.geofence.pojo.vo.GeofenceVO;
import cn.tedu.ivos.geofence.service.GeofenceService;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class GeofenceServiceImpl implements GeofenceService {
    @Autowired
    private GeofenceMapper geofenceMapper;

    @Autowired
    private VehicleMapper vehicleMapper;
    @Override
    public List<GeofenceVO> selectGeofence(GeofenceQuery geofenceQuery) {
        log.debug("车辆围栏列表显示业务：geofenceQuery={}",geofenceQuery);
        List<GeofenceVO> list = geofenceMapper.selectGeofence(geofenceQuery);
        return list;
    }

    @Override
    public void saveGeofence(GeofenceParam geofenceParam) {
        log.debug("保存电子围栏业务：geofenceParam={}",geofenceParam);
        Geofence geofence = new Geofence();
        BeanUtils.copyProperties(geofenceParam,geofence);
        if(geofence.getId()!=null){
            geofence.setUpdateTime(new Date());
            geofenceMapper.update(geofence);
        }else{
            geofence.setStatus("1");
            geofence.setCreateTime(new Date());
            geofenceMapper.saveGeofence(geofence);
        }
    }

    @Override
    public void changeStatus(Long id, String status) {
        Geofence geofence = new Geofence();
        geofence.setId(id);
        geofence.setStatus(status);
        geofence.setUpdateTime(new Date());
        geofenceMapper.update(geofence);
    }

    @Override
    public void deleteGeo(Long id) {
        log.debug("删除围栏业务：id={}",id);
//        需求：需要判断改围栏上是否还有绑定车辆，如果有绑定车辆，不能删除！
        VehicleQuery vehicleQuery = new VehicleQuery();
        vehicleQuery.setGeofenceId(id);
        List<VehicleVO> list = vehicleMapper.selectVehicle(vehicleQuery);
//        判断list是否为空，如果为空，可以删除围栏，如果不为空，说明围栏上还有绑定的车辆，不能删除
        if(list.size()>0 && list!=null){
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }else{
            geofenceMapper.delete(id);
        }
    }
}
